//
//  XYSessionManager.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/12.
//  Copyright © 2015年 小熊猫. All rights reserved.
//
/*
自定义
*/

import UIKit
import AFNetworking

enum HTTPStye:String{
    case POST = "POST"
    case GET = "GET"
}
//外部链接地址
private let APP_ROOT_URL = "https://api.weibo.com/"

class XYSessionManager: AFHTTPSessionManager {

    private let APP_KEY = "427735295"
    private  let APP_SECRET = "32d447242fe16d7f612021ce9aa685b7"
    //回调网址
    private  let REDIRECT_URL = "http://www.baidu.com"
    
    //给网络请求创建一个单例
    static let sharedManager:XYSessionManager = {
        let url = NSURL(string: APP_ROOT_URL)
        //设置单例对象的默认头网址和json的读取文件类型
        let manager = XYSessionManager(baseURL: url)
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return manager
    }()

    
    //拼接请求授权的网址
    func loadOAuthUrl( ) -> NSURL{
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(REDIRECT_URL)"

        return NSURL(string: urlString)!
    }
    
    
    //获取授权(token)的方法
    func loadSinaToken(code:String,complition:(dict:[String : AnyObject]?,error:NSError?) -> () ){

        let urlString = "oauth2/access_token"
        //自定义一个字典,把请求数据的参数包装在里面
        let parameters = [
            "client_id" : APP_KEY,                         //申请应用时分配的AppKey
            "client_secret" : APP_SECRET,           //申请应用时分配的AppSecret
            "grant_type" : "authorization_code",   //请求的类型，填写authorization_code
            "code" : code,                                      //调用authorize获得的code值
            "redirect_uri" : REDIRECT_URL           //回调地址，需需与注册应用里的回调地址一致
        ]
        
        reqeustJSON(.POST, urlString: urlString, parameters: parameters,complition:complition)
    }
    
    //请求用户信息
    func loadUserInfo(token:String,uid:String,complition:(dict:[String : AnyObject]?,error:NSError?) -> ()){
        let urlSting = "2/users/show.json"
        let parameters = [
            "access_token":token,
            "uid":uid
        ]
        reqeustJSON(.GET, urlString: urlSting, parameters: parameters, complition: complition)
    }
    
    //请求微博数据
    func loadSinaWeibo(token:String,max_id:Int = 0,since_id:Int = 0, complition:(dict:[String : AnyObject]?,error:NSError?) -> ()){
        let urlString = "2/statuses/friends_timeline.json"
        let parameters = [
            "access_token":token
            //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
            ,"since_id":"\(since_id)"
            //若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
            ,"max_id":"\(max_id)"
        ]
        
        reqeustJSON(.GET, urlString: urlString, parameters: parameters, complition: complition)
    }
    
    
  //这个是封装AFN的网络请求
    private func reqeustJSON(stye:HTTPStye,urlString:String,parameters:[String:AnyObject],complition:(dict:[String : AnyObject]?,error:NSError?) -> () ){
        

        //请求成功的闭包
        let successBlock = { (task:NSURLSessionDataTask,result:AnyObject) -> () in
            if let info = result as? [String:AnyObject]{
                complition(dict: info, error: nil)
            }else{
                
                //失败参数有待解惑~~~~!
                complition(dict: nil, error :NSError(domain: "", code: -10001, userInfo: ["error":"请求失败"]))
            }
        }
        //请求失败的闭包
        let failureBlock = { (task:NSURLSessionDataTask,error:NSError) -> () in
            complition(dict: nil, error: error)
        }
        
        //封装请求
        if stye == HTTPStye.GET{
            GET(urlString, parameters: parameters, success: successBlock, failure: failureBlock )
        }else{
            POST(urlString, parameters: parameters, success: successBlock, failure: failureBlock )
        }
        
    }
    
    
    
    
}
























